from time import process_time
from PySide6.QtWidgets import  QTableWidgetItem,QDialog
from PySide6.QtCore import Qt,Signal,QObject

from ui.dialog_ui import Ui_DownloadDialog


class DownloadDialog(QObject):
    downloadRequested = Signal(str, int)   # 文件名, 行号
    deleteRequested = Signal(str, int)     # 文件名, 行号
    downloadConfirmed = Signal()
    downloadCanceled = Signal()
    dialogClosed = Signal()

    # 新增：跨线程安全更新 UI 的信号
    fileListArrived = Signal(list)
    # 可选：后面还要做进度/完成的 UI 更新，也可以提前加
    updateProgress = Signal(int, str)   # row, text

    def __init__(self, parent=None):
        super().__init__(parent)
        self.dialog = QDialog()
        self.dl_dialog = Ui_DownloadDialog()
        self.dl_dialog.setupUi(self.dialog)

        self.files_list = []     # 文件列表清空
        self.last_len = 0   # dialog 上次接收数据长度
        
        # 绑定Dialog信号，单元格点击事件
        self.dl_dialog.tableWidget.cellPressed.connect(self.on_cell_clicked)
         # dialog按钮绑定
        self.dl_dialog.buttonBox.accepted.connect(self.download_confirm)
        self.dl_dialog.buttonBox.rejected.connect(self.download_cancel)
        self.dialog.finished.connect(self.dialog_closed)

        # 把信号连接到 UI 更新槽（保证在主线程执行）
        self.fileListArrived.connect(self.dialog_table_fill)
        self.updateProgress.connect(self._set_progress_cell)

    # dilog表头初始化
    def dialog_table_init(self):
        self.dl_dialog.tableWidget.clearContents()   
        # 表格清空
        self.dl_dialog.tableWidget.setRowCount(0)
        self.dl_dialog.tableWidget.setColumnCount(0)
        # 下载对话框初始化
        self.dl_dialog.tableWidget.setColumnCount(5)
        self.dl_dialog.tableWidget.setHorizontalHeaderLabels(["下载数据","文件名称","文件大小","下载进度","删除数据"])
        # 设置水平表头居中
        self.dl_dialog.tableWidget.horizontalHeader().setDefaultAlignment(Qt.AlignmentFlag.AlignCenter)
        # 设置垂直表头居中
        self.dl_dialog.tableWidget.verticalHeader().setDefaultAlignment(Qt.AlignmentFlag.AlignCenter)
        self.dl_dialog.tableWidget.setAlternatingRowColors(True)


    def on_cell_clicked(self, row, column):
        if column == 0:
            # “下载”列被单元格点击
            self.click_row = row
            self.download_file_name = None
            file_item = self.dl_dialog.tableWidget.item(row, 1)
            if file_item:
                self.download_file_name = file_item.text()
                # print(f"点击下载按钮，文件名：{self.download_file_name}")
                self.downloadRequested.emit(self.download_file_name, row)
        if column ==4:
            # 删除列单元格被点击
            dell_item = self.dl_dialog.tableWidget.item(row, 1)
            if dell_item:
                dell_file = dell_item.text()
                # print(f"点击删除按钮，文件名：{dell_file}, 行号：{row}")
                self.deleteRequested.emit(dell_file, row)
                

        
    # dialog数据填充
    def dialog_table_fill(self,filelist):
        # 解析“文件名.csv + 数字(字节)”形式，填充文件名与大小
        def parse_name_and_size(s: str):
            pos = s.rfind('.csv')
            if pos != -1:
                name = s[:pos + 4]
                tail = s[pos + 4:]
            else:
                name = s
                tail = ""
            # 提取连续数字作为大小
            i = 0
            while i < len(tail) and tail[i].isspace():
                i += 1
            j = i
            while j < len(tail) and tail[j].isdigit():
                j += 1
            size_val = int(tail[i:j]) if j > i else None
            return name, size_val
    
        # 下载对话框表格填充
        table = self.dl_dialog.tableWidget

        files_len = len(filelist)
        if files_len > self.last_len:
            for i in range(self.last_len,files_len):
                row = table.rowCount()
                table.insertRow(row)
                # 第一列 下载
                download_cell = QTableWidgetItem("下载")
                raw_entry = filelist[i]
                file_name, file_size = parse_name_and_size(raw_entry)
                # 第二列 设置文件名文本
                file_item = QTableWidgetItem(file_name)
                file_item.setFlags(file_item.flags() & ~Qt.ItemFlag.ItemIsEditable)
                file_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
                
                #第三列 文件大小（转为KB，两位小数，不可编辑、居中）
                if file_size is None:
                    size_text = ""
                elif file_size <= 0:
                    size_text = "0.00 K"
                else:
                    size_k = file_size / 1024
                    size_text = f"{size_k:.2f} K"
                size_item = QTableWidgetItem(size_text)
                size_item.setFlags(size_item.flags() & ~Qt.ItemFlag.ItemIsEditable)
                size_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
                # 第四列 下载进度列（初始为“0%”）
                progress_item = QTableWidgetItem("0%")
                progress_item.setFlags(progress_item.flags() & ~Qt.ItemFlag.ItemIsEditable)
                progress_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
                # 第五列 删除列
                dele_item = QTableWidgetItem("删除")
                dele_item.setFlags(dele_item.flags() & ~Qt.ItemFlag.ItemIsEditable)
                dele_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
                # 填充目录
                table.setItem(row, 0, download_cell)
                table.setItem(row, 1, file_item)
                table.setItem(row, 2, size_item)
                table.setItem(row, 3, progress_item)
                table.setItem(row, 4, dele_item)
            
            table.resizeColumnsToContents()
            # 根据内容撑开宽度
            total_width = table.verticalHeader().width() + 2 * table.frameWidth()
            for c in range(table.columnCount()):
                total_width += table.columnWidth(c)
            if table.verticalScrollBar().isVisible():
                total_width += table.verticalScrollBar().width()
            table.setMinimumWidth(total_width)

        self.last_len = len(filelist)

    # 新增：设置进度单元格的槽函数（主线程执行）
    def _set_progress_cell(self, row: int, text: str):
        try:
            if row is not None and row >= 0:
                item = QTableWidgetItem(text)
                item.setFlags(item.flags() & ~Qt.ItemFlag.ItemIsEditable)
                item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
                self.dl_dialog.tableWidget.setItem(row, 3, item)
        except Exception:
            pass



    def download_confirm(self):
        self.downloadConfirmed.emit()

    def download_cancel(self):
        self.downloadConfirmed.emit()

    def dialog_closed(self):
        self.dialogClosed.emit()